/*
*** (C) 2008 UCMai.com ***

Subj: 公共函数库
Auth: zhouyongtai
Date: 2008-09-05
*/
document.oncontextmenu = function(e){
	e=e || window.event;
//	e.cancelBubble = true;
//	e.returnValue = false;

	if(window.event) {
		e.cancelBubble = false;
		e.returnValue = false;
	}
	else {
		e.stopPropagation();
		e.preventDefault();
	}
};
function now(){
	return +new Date;
}
var $Name = function(name){
	return (document.getElementsByName(name));
}

var showLoading = function(msg,progressText,el){
	Ext.MessageBox.show({//自定义对话框
		msg:msg,
		progressText:progressText,
		width:300,
		wait:true,
		waitConfig: {interval:200},
		icon:'ext-mb-save',
		animEl:el
	});
}

var hideLoading = function(){
	Ext.MessageBox.hide();
}
Ext.HandleTip = function(){
	var msgCt;
	function createBox(t, s){
		return ['<div class="msg">',
		'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
		'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3><span class="fleft">', t, '</span><span class="fright hand" id="closebutton"><img src="/img/tab-close.gif" /></span></h3><div style="clear:both;">', s, '</div></div></div></div>',
		'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
		'</div>'].join('');
	}
	return {
		msg : function(title, format,t){
			if(typeof t=='undefined'){
				t = 3;
			}
			if(!msgCt){
				msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
			}
			msgCt.alignTo(document, 't-t');
			var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
			var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
			m.slideIn('t').pause(t).ghost("t", {remove:true});
			Ext.get('closebutton').on('click',function(){
				m.remove();
			});
		}
	};
}();

var Cookies = {};
Cookies.set = function(name, value){
	var argv = arguments;
	var argc = arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : '/';
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
		((expires==null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path==null) ? "" : ("; path=" + path)) +
		((domain==null) ? "" : ("; domain=" + domain)) +
		((secure==true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = document.cookie.indexOf('zyt_app_') + 9;
	var j = document.cookie.indexOf(arg, i) + arg.length;
	var k = document.cookie.indexOf('&', j); 
	return document.cookie.substring(j, k);
	/*
	while(i < clen){
		j = i + alen;
		alert(document.cookie.substring(i, j));
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);

		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;*/
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
	var endstr = document.cookie.indexOf(";", offset);
	if(endstr == -1){
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
};

var ajaxRequest = function(url, args, callback) {
	//args = args ? args : [];
	args = args ? args : {};
	Ext.Ajax.request({
		url: url,
		params: Ext.urlEncode(args),
		method: 'POST',
		callback: function(request, success, response) {
			if (!success) {
				alertError('未知错误!<br>请稍候再试.');
				return;
			}
			var bError,serverMsg,serverResult;
			if(response.responseText!=''){
				serverMsg = Ext.decode(response.responseText);
				bError = (typeof serverMsg.error === 'undefined'?false:true);
				serverResult=(typeof serverMsg.result === 'undefined'?'':serverMsg.result);
			}else{
				bError = false;
				serverResult = '';
			}
			if(bError){
				alertError(serverMsg.error);
				return;
			}
			callback(serverResult);
		}
	});
};

var ImportMod = function(url,callback){
	Ext.Ajax.request({
		url: 'js/class/'+url,
		method: 'GET',
		callback: function(request, success, response) {
			permit();
			if (!success) {
				alertError('未知错误!<br>请稍候再试.');
				return;
			}

			var headerDom = document.getElementsByTagName('head').item(0);
			if(headerDom.getElementsByTagName("script").length==1){
				headerDom.removeChild(headerDom.getElementsByTagName("script")[0]);
			}

			var jsDom = document.createElement('script');
			jsDom.type = 'text/javascript';
			jsDom.language = 'javascript';
			jsDom.id = url;
			jsDom.defer = "defer";
			jsDom.text = response.responseText;
			headerDom.appendChild(jsDom);
			callback();
		}
	});
};

var loadMod = function(config){
	var mainpanel=Ext.getCmp('mainpanel');

	if(mainpanel != null) {
		if (LABS_NUM == 0)
		{
		mainpanel.items.each(function(item){
			mainpanel.remove(item);
			item.setDisabled(true);
			LABS_NUM--;
		});}
	}
	if (!mainpanel.getItem(config.id)){
		if(mainpanel.items.length>6){
			Ext.MessageBox.alert('系统提醒', '最多只能打开7个窗口，请关闭一些窗口。');
			//delete new config.grid;
			return;
		}else{
			mainpanel.add(new config.grid());
			mainpanel.getItem(config.id).setTitle(config.title);
		}
		//LABS_NUM++;
	}
	mainpanel.setActiveTab(mainpanel.getItem(config.id));
	
	if(typeof config.condition==="object"){
		new config.grid().reload(config.condition);
	}
};
var loadPanel = function(config){
	var mainpanel=Ext.getCmp('mainpanel');
	var panel = new Ext.Panel({
		//contentEl:'Configpanel',将写好的HTML放入Panel中
		border:false,
		layout:'fit',
		html:'<div id="Configpanel" marginheight="0" marginwidth="0" width="100%" height="'+ sysCenterHeight +'"></div>'
	});
	if(mainpanel != null) {
		if(typeof(config.depth) == 'undefined') {
			config.depth = 0;
		}
		if (LABS_NUM == 0)
		{
			mainpanel.items.each(function(item){
			mainpanel.remove(item);
			item.setDisabled(true);
			LABS_NUM--;
		});
		}
	
	}
		mainpanel.add(panel);
		mainpanel.getItem(0).setTitle(config.title);
		//Ext.getCmp('mainpanel').doLayout();
		LABS_NUM++;
//	if (!mainpanel.getItem(config.id)){
//		
//	}
	//mainpanel.setActiveTab(mainpanel.getItem(config.id));
}

var loadPage = function(config){
	var mainpanel=Ext.getCmp('mainpanel');
	if(mainpanel!=null) {
		if(typeof(config.depth) == 'undefined') {
			config.depth = 0;
		}
		for(var minT = config.depth;LABS_NUM>=minT;LABS_NUM--){
			var item = mainpanel.getItem(LABS_NUM);
			if(item){
				mainpanel.remove(item);
				item.setDisabled(true);
			}
		}
	}
	var oMainPanel = new Ext.Panel({
		id:'page' + config.depth,
		border:false,
		layout:'fit',
		html:'<iframe src="'+ config.url +'"  marginheight="0" marginwidth="0" scrolling="auto" frameborder="0" width="100%" height="'+ sysCenterHeight +'"></iframe>'
	});
	mainpanel.add(oMainPanel);
	mainpanel.getItem(config.depth).setTitle(config.title);
	mainpanel.setActiveTab(0);
	LABS_NUM++;
};

var $import = function(path,type,title){
	var s,i;
	if(type == "js"){
		var ss = document.getElementsByTagName("script");
		for(i=0;i<ss.length;i++){
			if(ss[i].src && ss[i].src.indexOf(path) != -1)return ss[i];
		}
		s = document.createElement("script");
		s.type = "text/javascript";
		s.src = path;
	}else if(type == "css"){
		var ls = document.getElementsByTagName("link");
		for(i=0;i<ls.length;i++){
			if(ls[i].href && ls[i].href.indexOf(path)!=-1)return ls[i];
		}
		s = document.createElement("link");
		s.rel = "alternate stylesheet";
		s.type = "text/css";
		s.href = path;
		s.title = title;
		s.disabled = false;
	}
	else return;
	var head = document.getElementsByTagName("head")[0];
	head.appendChild(s);
	return s;
};

var detectAcl = function(url){
//	Ext.Ajax.request({
//		url:url,
//		method:'GET',
//		callback:function(request, success, response){
//			if (!success) {
//				alertError('未知错误!<br>请稍候再试.');
//				return;
//			}
//			var bError,serverMsg;
//			if(response.responseText!=''){
//				serverMsg = Ext.decode(response.responseText);
//				bError = (typeof serverMsg.error === 'undefined'?false:true);
//			}else{
//				bError = false;
//			}
//			if(bError){
//				alertError(serverMsg.error);
//				return;
//			}
//		}
//	});
};

var emptyText = function() {
	return '';
}

var confirm = function(yesCallback) {
	Ext.MessageBox.confirm('提示', '您确定要删除所选择的记录吗?', function(btn) {
		if (btn == 'yes') yesCallback();
	});
}

var confirmEx = function(act,title,yesCallback) {
	Ext.MessageBox.confirm('提示', '您确定要' + act + '所选择的' + title + '吗?', function(btn) {
		if (btn == 'yes') yesCallback();
	});
}

var saveform = function(yesCallback) {
	Ext.MessageBox.confirm('提示', '您确定要保存所选择的记录吗?', function(btn) {
		if (btn == 'yes') yesCallback();
	});
}

var alertError = function(msg) {
	Ext.MessageBox.show({
	   title: '错误', msg: msg, icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK
	});
}

var alertTip = function(msg){
	Ext.MessageBox.show({
	   title: '提示', msg: msg, icon: Ext.MessageBox.WARNING, buttons: Ext.MessageBox.OK
	});
}

var setStyle = function(styletitle) {
	var i;
	var links;
	var eflag = false;
	links = document.getElementsByTagName("link");
	
	if(styletitle === "" || styletitle === null){
		for(var i=0;links[i];i++){
			if(links[i].getAttribute("rel").indexOf("style") != -1 && links[i].getAttribute("title")) {
				links[i].disabled = true;
			}
		}
		return;
	}

	for(i=0; links[i]; i++) {
		if(links[i].getAttribute("rel").indexOf("style") != -1 && links[i].getAttribute("title")) {
			links[i].disabled = true;
			if(links[i].getAttribute("title").indexOf(styletitle) != -1)
			{
				links[i].disabled = false;
				eflag=true;
			}
		}
	}
	if(!eflag){
		$import("css/"+styletitle+"/css/css.css","css",styletitle);
		setStyle(styletitle);
	}
}

var setTheme = function(){
	setStyle(Cookies.get("UCM_THEME"));
}

var PermitWindow = function(config) {
	this.config = config;
	this.logon = function() {
		var frm = this.form.getForm();
		if (!frm.isValid()) {
			return;
		}
		showLoading("正在验证，请稍侯...","正在登录中...");
		ajaxRequest(serverUrl_Login + 'logon', frm.getValues(), function() {
			hideLoading();
			window.location.href = 'default.html';
		}.createDelegate(this));
	};
	this.form = new Ext.FormPanel({
		labelWidth: 60,
		defaults: {width:120, allowBlank:false},
		defaultType: 'textfield',
		border: false,
		bodyStyle: 'padding:10px',
		frame:true,
		keys: {
			key: Ext.EventObject.ENTER,
			fn: this.logon.createDelegate(this)
		},
		items: [{
			fieldLabel: '用户名',
			id:'loginUserName',
			name: 'username',
			maxLength: 50
		}, {
			fieldLabel: '密码',
			name: 'pass',
			inputType: 'password',
			maxLength: 30
		}]
	});

	PermitWindow.superclass.constructor.call(this, {
		title: '管理员登录',
		width: 250,
		height: 150,
		resizable: false,
		closable: false,
		constrain: true,
		onEsc: Ext.emptyFn,
		layout: 'fit',
		items: this.form,
		iconCls: 'permit',
		modal: this.config,
		buttons: [{
			text: '登录',
			handler: this.logon.createDelegate(this)
		}]
	});

	/*
	this.on('beforeshow', function() {
		Ext.getCmp('mainpanel').body.mask();
	});
	this.on('beforehide', function() {
		Ext.getCmp('mainpanel').body.unmask();
	});
	*/
};

//继承类Ext.Window，并添加hide,showLogin方法到PermitWindow的prototype对象中，如果PermitWindow的prototype对象中有同名方法则覆盖。
Ext.extend(PermitWindow, Ext.Window, {
	hide: function() {
		if (this.isVisible()) {
			this.form.destroy();
			PermitWindow.superclass.hide.apply(this, arguments);
		}
	},
	showLogin: function() {
		this.show();
	}
});

var permit = function(){
	ajaxRequest(serverUrl_Permit + "&key=" + now(),{action:'permit'}, function(result) {
		if(result === "permit"){
			var permitWindow = new PermitWindow(true);
			permitWindow.showLogin();
			Ext.getCmp('loginUserName').focus(true,true);
		}
	});
};

var getSysUser = function(){
	ajaxRequest(serverUrl_AdminUserGet + 'getuser&key='+now(),{action:'getuser'},function(result){
		var rec = result.split('^');
		Ext.get('user').dom.innerHTML = '<font color="red">' + rec[0] + '</font>&nbsp;欢迎您！';
		if(rec[1]>0) {
			//Ext.get('user').dom.innerHTML = '<span class="fontred"><b>共有 ' + rec[1] + ' 笔待发货订单！</b></span>&nbsp;&nbsp;' + Ext.get('user').dom.innerHTML;
			top.document.getElementById('se_o_alarm').src = '/img/alarm.wav';
		}
	})
};

AppFunMenu = function() {
    AppFunMenu.superclass.constructor.call(this, {
        width: 198,
        rootVisible:false,
        lines:false,
        autoScroll:true,
        root: new Ext.tree.TreeNode(),
        collapseFirst:false,
		rootVisible:false,
		border:false
    });
    this.funmenu = this.root;
};
Ext.extend(AppFunMenu, Ext.tree.TreePanel, {
    addFun : function(attrs){
        Ext.apply(attrs, {
            iconCls: 'funmenu-icon',
            leaf:true,
            cls:'funmenu'
        });
        var node = new Ext.tree.TreeNode(attrs);
		node.on("click",attrs.handler);
        this.funmenu.appendChild(node);
        return node;
    }
});

var currentPageBaseHREF="http://";

Ext.namespace('Ext.ux');
Ext.ux.ImageButton = function(cfg) {  
	Ext.ux.ImageButton.superclass.constructor.call(this, cfg);  
};  
Ext.extend(Ext.ux.ImageButton, Ext.Button, {
	onRender : function(ct, position) {  
		this.disabledImgPath = this.disabledImgPath || this.imgPath;  
		var tplHTML = '<div style="padding-bottom:10px"><img src="{imgPath}" mce_src="{imgPath}" border="0" width="{imgWidth}" height="{imgHeight}" alt="{tooltip}" style="cursor: {cursor};" mce_style="cursor: {cursor};"/>{imgText:htmlEncode}</div>';  
		var tpl = new Ext.Template(tplHTML);  
		var btn, targs = {  
			imgPath : this.disabled ? this.disabledImgPath : this.imgPath,  
			imgWidth : this.imgWidth || "",  
			imgHeight : this.imgHeight || "",  
			imgText : this.text || "",  
			cursor : this.disabled ? "default" : "pointer",  
			tooltip : this.tooltip || ""  
		};  
		btn = tpl.append(ct, targs, true);  
		btn.on("click", this.onClick, this);  
		if (this.cls) {  
			btn.addClass(this.cls);  
		}  
		this.el = btn;  
		if (this.hidden) {  
			this.hide();  
		}
	},  
	disable : function(newImgPath) {  
		var replaceImgPath = newImgPath || this.disabledImgPath;  
		if (replaceImgPath)  
			this.el.dom.firstChild.src = replaceImgPath;  
		this.disabled = true;  
	},  
	enable : function(newImgPath) {  
		var replaceImgPath = newImgPath || this.imgPath;  
		if (replaceImgPath)  
			this.el.dom.firstChild.src = replaceImgPath;  
		this.disabled = false;  
	}
});  
Ext.reg('imagebutton', Ext.ux.ImageButton);

function getNo(){
	var d = new Date();
	var y = d.getFullYear();
	var m = d.getMonth();
	var day = d.getDate();
	var h = d.getHours();
	var minutes = d.getMinutes();
	var s = d.getSeconds();
	var ms = d.getMilliseconds();
	var no = y + (m<10?"0"+m:m).toString() + (day<10?"0"+day:day).toString() + (h<10?"0"+h:h).toString() + (minutes<10?"0"+minutes:minutes).toString() + (s<10?"0"+s:s).toString() + "0" + (ms<10?"00"+ms:(ms<100?"0"+ms:ms)).toString();
	return no;
}